package com.gzz.socket.bio;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Formatter;

/**
 * 这是一个单线程BIOServer
 */
public class BioServerDemo {

    public static void main(String[] args) throws IOException {
        // 创建ServerSocket，并绑定端口
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务启动成功");
        // 单线程
//        while (true) {
//            Socket socket = serverSocket.accept();
//            System.out.println("连接成功");
//            System.out.println("准备接收数据");
//            byte[] bytes = new byte[1024];
//            socket.getInputStream().read(bytes);
//            System.out.println("接收到了数据：" + new String(bytes));
//        }
        // BIO实现并发
        while (true) {
            Socket socket = serverSocket.accept();
            new Thread(()->{
                System.out.println("连接成功");
                System.out.println("准备接收数据");
                byte[] bytes = new byte[1024];
                try {
                    OutputStream os = socket.getOutputStream();
                    BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
                    // 分配空间512
                    ByteBuffer buffer = ByteBuffer.allocate(512);
                    byte[] temp = new byte[256];
                    int len =0;
                    System.out.println("DTU-NO::start:" + bis.available());
                    while((len = bis.read(temp)) != -1) {
                        System.out.println("DTU-NO::temp:["+len+"]" + ByteToHex(temp));
                        buffer.put(temp, 0, len);
                        if(len<256) break;
                    }

                    buffer.flip();
                    System.out.println("DTU-NO::buffer:" + ByteToHex(buffer.array()));
                    byte[] ret = new byte[buffer.limit()];
                    buffer.get(ret, buffer.position(), buffer.limit());
                    buffer.clear(); // 回到初始状态
                    //socket.getInputStream().read(bytes);
                    System.out.println("DTU-NO::buffer:" + ByteToHex(ret));
                    //
                    buffer.clear();
                    while((len = bis.read(temp)) != -1) {
                        System.out.println("DTU-NO::temp:["+len+"]" + ByteToHex(temp));
                        buffer.put(temp, 0, len);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("接收到了数据：" + new String(bytes));
            }).start();
        }
    }
    public static String ByteToHex(byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
            formatter.format("%02x", b);
        String result = formatter.toString();
        formatter.close();
        return result.toUpperCase();
    }

}